import { defineStore } from 'pinia'
import { ref } from 'vue'
import { request } from '@/api/request'

export const useAuthStore = defineStore('auth', () => {
    const token = ref(localStorage.getItem('token') || null)
    const loading = ref(false)
    const error = ref(null)

    // 获取token
    async function fetchToken() {
        loading.value = true
        error.value = null

        try {
            const response = await request({
                url: '/login',
                method: 'post',
                data: {
                    username: 'admin',
                    password: 'admin123'
                }
            })

            setToken(response.data.token)
            return response.data.token
        } catch (err) {
            error.value = err.response?.data?.message || err.message
            throw err
        } finally {
            loading.value = false
        }
    }

    // 设置token
    function setToken(newToken) {
        token.value = newToken
        localStorage.setItem('token', newToken)
    }

    // 清除token
    function clearToken() {
        token.value = null
        localStorage.removeItem('token')
    }

    return {
        token,
        loading,
        error,
        fetchToken,
        setToken,
        clearToken
    }
})